package cn.icast.netty.c3;

import io.netty.bootstrap.Bootstrap;


import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;

import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.util.Scanner;
@Slf4j
public class ChannelFutureClient {
    public static void main(String[] args) throws InterruptedException {
        NioEventLoopGroup group = new NioEventLoopGroup();
        ChannelFuture channelFuture = new Bootstrap()

                .group(group)

                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        //指定日志级别
                        ch.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG));
                       ch.pipeline().addLast(new StringEncoder());
                    }
                }).connect(new InetSocketAddress("localhost", 8080));
        Channel channel = channelFuture.sync().channel();
        log.debug("chu{}...",channel);
        new Thread( () -> {
            Scanner s=new Scanner(System.in);
            while (true){
                String line = s.nextLine();
                if("q".equals(line)){
                    channel.close();// close异步操作1s之后

                    break;
                }
                channel.writeAndFlush(line);
            }
        } ,"input").start();

        // 获取closedFuture对象，1）同步处理关闭， 2）异步处理关闭
        ChannelFuture closedFuture = channel.closeFuture();

        //第一种
      /*  System.out.println("waiting close...");
        closedFuture.sync();
        log.debug("处理关闭之后的操作");*/

        //第二种
        closedFuture.addListener((ChannelFutureListener) future -> {
            log.debug("处理关闭之后的操作");
            group.shutdownGracefully();
        });
    }
}
